package com.hwatsang.service.impl;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;

public class FileService implements InitializingBean {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(FileService.class);
	
	private String resourceDir;
	private String imageDir;
		
	/**
	 * Store the product image file to the file system
	 * @param file
	 * @return The full path to the file.
	 * @throws IOException 
	 */
	public String storeProductImg(String productId, File file, String imgName) throws IOException {
				
		LOGGER.info("Storing image {} for product {}.", imgName, productId);
		
		// file name will be "<product_id>.<ext>"
		String fileName = productId + StringUtils.substring(imgName, StringUtils.lastIndexOf(imgName, '.'));		
		String destFilePath = imageDir + "/product/" + fileName;
		storeFile(destFilePath, file);
		
		return destFilePath; 
	}
	
	public String updateProductImg(String productId, String oldFileName, File file, String imgName) throws IOException {
		
		LOGGER.info("Updating product's image to {}.", imgName);
		
		File oldFile = new File(oldFileName);
		if(oldFile.isFile()) {
			oldFile.delete();
		}
		
		return storeProductImg(productId, file, imgName);
	}
		
	private void storeFile(String savePath, File file) throws IOException {
		File fileToStore = new File(savePath);
		FileUtils.copyFile(file, fileToStore);
	}
	
	public void setResourceDir(String resourceDir) {
		this.resourceDir = resourceDir;
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		this.imageDir = this.resourceDir + "/images";		
	}
}
